package cn.jiyun.controller;

import cn.jiyun.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("common")
//获取配置文件
public class CommonController {
////    注入属性
    @Value("${reggie.path}")
    private String path;

    @PostMapping("upload")
    public R upload (MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String substring = filename.substring(filename.lastIndexOf("."));
         String  name=  UUID.randomUUID().toString()+ substring;

        File f=new File(path);
        if (!f.exists()){
            f.mkdir();
        }
         File file1=new File(f,name);
        file.transferTo(file1);
        return R.success(name);

    }

    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws IOException {
        File file=new File(path,name);
        FileInputStream fileInputStream= new FileInputStream(file);
        ServletOutputStream servletOutputStream=response.getOutputStream();
        byte []by=new byte[1024];
        int len=0;
        while ((len=fileInputStream.read(by))!=-1){
            servletOutputStream.write(by,0,len);

        }
        fileInputStream.close();


    }

}
